#!/usr/bin/env python
# coding: utf-8

# # 地理/逆地理编码

# ### 介绍  
# 地理编码/逆地理编码 API 是通过 HTTP/HTTPS 协议访问远程服务的接口，提供结构化地址与经纬度之间的相互转化的能力。  
# （结构化地址的定义： 首先，地址肯定是一串字符，内含国家、省份、城市、区县、城镇、乡村、街道、门牌号码、屋邨、大厦等建筑物名称。按照由大区域名称到小区域名称组合在一起的字符。一个有效的地址应该是独一无二的。）  
# ### 应用场景  
# * 地理编码：将详细的结构化地址转换为高德经纬度坐标。且支持对地标性名胜景区、建筑物名称解析为高德经纬度坐标。  
# （例：结构化地址举例：北京市朝阳区阜通东大街6号转换后经纬度：116.480881,39.989410） 
# 
# * 逆地理编码：将经纬度转换为详细结构化的地址，且返回附近周边的POI、AOI信息。  
# （例：116.480881,39.989410 转换地址描述后：北京市朝阳区阜通东大街6号）  
# 

# ### A-1 地理编码
# def定义函数名geocode，定义参数

# In[5]:


import pandas as pd
import requests
key_jw ="99b6fd576c6cb06dc071b44d30935237"


# In[13]:


def geocode(address,city=None,batch=None,sig=None)->dict:
    """获取地理编码"""
    url = 'https://restapi.amap.com/v3/geocode/geo?parameters'
    params={
        'key': key_jw,
        'address':address,
        'city':city,
        'batch':batch,
        'sig':sig, 
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data
革新路 = geocode(address='广东省广州市海珠区革新路鹅潭明珠苑')
print(革新路)
df_革新路地理编码 = pd.json_normalize(革新路['geocodes'])
display(df_革新路地理编码)
革新路地理编码 = 革新路['geocodes'][0]['location']
print("革新路地理编码:",革新路地理编码)


# ### 逆地理编码
#  A-2 基础逆地理编码分析

# In[10]:


import requests
import json
import pandas as pd


# In[14]:


def regeocode(key,location='113.679287,23.632575',poitype=None,radius=None,extensions="all",batch=False,roadlevel=None,sig=None,callback=None,homeorcorp=None) ->dict:
    '''获得高德API逆地理编码'''
    url = 'https://restapi.amap.com/v3/geocode/regeo?parameters'
    params = {
        'key':key_jw,
        'location':location,
        'poitype':poitype,
        'radius':radius,
        'extensions':extensions,
        'batch':batch,
        'roadlevel':roadlevel,
        'sig':sig,
        'output':'json',
        'callback':callback,
        'homeorcorp':homeorcorp
    }
    r = requests.get(url,params=params)
    result = r.json()
    return result
革新路 = regeocode(key=key_jw,location="113.251893,23.092342",extensions="all")
print(革新路)
df_革新路 = pd.json_normalize(革新路)
df_革新路


# #  路径规划

# ### 介绍  
# 路径规划API是一套以HTTP形式提供的步行、公交、驾车查询及行驶距离计算接口，返回JSON 或 XML格式的查询数据，用于实现路径规划功能的开发。 
# 
# ### 应用场景  
# * 无需展现地图的场景下，进行线路查询，如以线路结果页形式展现换乘方案；
# * 根据返回线路数据，自行开发线路导航。
# 

# ### 步行

# In[15]:


import requests
import json
import pandas as pd


# In[18]:


def walk(key,origin='113.679287,23.632575',destination='113.632403,23.616941',output=json,sig=None,callback=None) ->dict:
    '''获取高德API步行路径规划'''
    url = 'https://restapi.amap.com/v3/direction/walking?parameters'
    params = {
        "key":key_jw,
        "origin":origin,
        "destination":destination,
        "sig":sig,
        "output":json,
        "callback":callback
        
    }
    r = requests.get(url,params=params)
    result = r.json()
    return result
road_walk = walk(key_jw,origin='113.679287,23.632575',destination = '113.632403,23.616941')
print(road_walk)
df_road_walk = pd.json_normalize(road_walk)
df_road_walk


# ### 公车路径规划

# In[20]:


def integrated(origin,destination,city,cityd=None,extensions='base',strategy=None,nightflag=0,date=None,time=None,sig=None)->dict:
    url = 'https://restapi.amap.com/v3/direction/transit/integrated?parameters'
    params={
        'key':key_jw,
        'origin':origin,
        'destination':destination,
        'city':city,
        'cityd':cityd,
        'extensions':extensions,
        'strategy':strategy,
        'nightflag':nightflag,
        'date':date,
        'output':'json'
    }
    response = requests.get(url,params=params)
    data = response.json()
    return data

# C-2 准备参数
中大南方 = geocode('广东省广州市从化区中山大学南方学院')
中大南方_location = 中大南方['geocodes'][0]['location']
革新路 = geocode('广东省广州市海珠区革新路鹅潭明珠苑')
革新路_location = 革新路['geocodes'][0]['location']
print("(起点)中大南方_location:",中大南方_location,"(终点)革新路_location:",革新路_location)

# C-3 公交路径规划
中大南方_革新路 = integrated(中大南方_location,革新路_location,city='广州',extensions='all')
print(中大南方_革新路)
df_bus = pd.json_normalize(中大南方_革新路)
df_bus


# ### 骑行路径规划

# In[21]:


import requests
import json
import pandas as pd


# In[22]:


def bike(key,origin='116.613190,23.269440',destination='116.602392,23.259433')->dict:
    '''获取高德API骑行路径规划'''
    url = 'https://restapi.amap.com/v4/direction/bicycling?parameters'
    key = '5e511d55ece1791b213c4ef41b428738'
    params = {
        "key":key_jw,
        "origin":origin,
        "destination":destination
    }
    r = requests.get(url,params=params)
    result = r.json()
    return result
road_bike = bike(key_jw,origin='116.613190,23.269440',destination='116.602392,23.259433')
print(road_bike)
df_road_bike = pd.json_normalize(road_bike['data'])
df_road_bike


# ### 货车路径规划

# In[23]:


import requests
import json
import pandas as pd


# In[29]:


def truck(key,origin = '116.613190,23.269440',destination = '113.679287,23.632575',size=2,originid=None,originidtype=None,destinationid=None,destinationtype=None,diu=None,strategy=None,waypoints=None,height=None,width=None,load=None,weight=None,axis=None,province=None,number=None,cartype=None,avoidpolygons=None,showpolyline=None,nosteps=None)->dict:  
    '''获取高德API货车路径规划'''   
    url = 'https://restapi.amap.com/v4/direction/bicycling?parameters'   
    params = {
        "key":key_jw,
        "origin":origin,
        "destination":destination,
        "size":size,
        "originid":originid,
        "originidtype":originidtype,
        "destinationid":destinationid,
        "diu":diu,
        "strategy":strategy,
        "waypoints":waypoints,
        "height":height,
        "width":width,
        "load":load,
        "weight":weight,
        "axis":axis,
        "province":province,
        "number":number,
        "cartype":cartype,
        "avoidpolygons":avoidpolygons,
        "showpolyline":showpolyline,
        "nosteps":nosteps,
        "output":json    }   
    r = requests.get(url,params=params)   
    result = r.json()  
    return result
road_truck = truck(key_jw,origin= '116.613190,23.269440',destination = '113.679287,23.632575',size=2)
print(road_truck)
df_road_truck = pd.json_normalize(road_truck)
df_road_truck


# ### 距离测量

# In[36]:


import requests
import json
import pandas as pd


# In[37]:


def distance(key='key',origin = '113.251893,23.092342',destination = '113.679287,23.632575',type=None,sig=None,output='json',callback=None)->dict:
    '''获取高德API测量距离'''
    url = 'https://restapi.amap.com/v3/distance?parameters'
    key = '5e511d55ece1791b213c4ef41b428738'
    params = {
        "key":key,
        "origin":origin,
        "destination":destination,
        "type":type,
        "sig":sig,
        "callback":callback,
        "output":json
    }

    r = requests.get(url,params=params)
    result = r.json()
    return result


# In[38]:


car_distance = distance(key='key_jw',origin='113.251893,23.092342',destination='113.679287,23.632575')
print(car_distance)
df_car_distance = pd.json_normalize(car_distance)
df_car_distance


# # 行政区域查询

# ### 介绍  
# 行政区域查询是一类简单的HTTP接口，根据用户输入的搜索条件可以帮助用户快速的查找特定的行政区域信息。

# In[39]:


import requests
import json
import pandas as pd


# In[40]:


def district(key,keywords='广州市',subdistrict=None,page=None,offset=None,extensions='base',filter=None,callback=None,output=json)->dict:
    '''获取行政区域'''
    url = 'https://restapi.amap.com/v3/config/district?parameters'
    params = {
        "key":key_jw,
        "keywords":keywords,
        "subdistrict":subdistrict,
        "page":page,
        "offset":offset,
        "extensions":extensions,
        "filter":filter,
        "callback":callback,
        "output":json
    }

    r = requests.get(url,params=params)
    result = r.json()
    return result


# In[41]:


行政区域 = district(key_jw,keywords='广州市',extensions='base')
print(行政区域)
df_行政区域 = pd.json_normalize(行政区域["districts"])
df_行政区域


# # 搜索POI

# ### 介绍  
# 搜索服务API是一类简单的HTTP接口，提供多种查询POI信息的能力，其中包括关键字搜索、周边搜索、多边形搜索、ID查询四种筛选机制。
# 
# ### 适用场景
# * 关键字搜索：通过用POI的关键字进行条件搜索，例如：肯德基、朝阳公园等；同时支持设置POI类型搜索，例如：银行
# * 周边搜索：在用户传入经纬度坐标点附近，在设定的范围内，按照关键字或POI类型搜索；
# * 多边形搜索：在多边形区域内进行搜索
# * ID查询：通过POI ID，查询某个POI详情，建议可同输入提示API配合使用

# In[42]:


import requests
import json
import pandas as pd


# In[50]:


def POI(keywords,types,city=None,citylimit=None,children=None,page=None,extensions='base',sig=None)->dict:
    """获取高德API的POI"""
    url = "https://restapi.amap.com/v3/place/text?parameters"
    params = {
    "key":key_jw,
    "keywords":keywords,
    "types":types,
    "city":city,
    "citylimit":citylimit,
    "children":children,
    "page":page,
    "extensions":extensions,
    "output":json
}
    # positional argument follows keyword argument（位置参数放在关键字参数之后）
    # pa 一定要放在前面，keyword argument放在末尾！！！可以
    r = requests.get(url,params=params)
    results = r.json()
    return results


# In[51]:


广州_麦当劳 = POI(keywords=None,types="麦当劳",city="广州市",children=1,extensions="all",page=3)
print(广州_麦当劳)
df_广州_麦当劳 = pd.json_normalize(广州_麦当劳["pois"])
df_广州_麦当劳


# # IP定位
# ### 介绍  
# IP定位是一个简单的HTTP接口，根据用户输入的IP地址，能够快速的帮用户定位IP的所在位置。
# 
# 

# In[54]:


import requests
import json
import pandas as pd


# In[55]:


def IP(key,ip=None,sig=None,output=json)->dict:
    '''获取高德API的IP定位'''
    url = " https://restapi.amap.com/v3/ip?parameters"
    params = {
        "key":key_jw,
        "ip":ip,
        "sig":sig,
        "output":json
    }
    r = requests.get(url,params=params)
    result = r.json()
    return result
IP定位 = IP(key_jw,ip=None,sig=None,output=json)
print(IP定位)
df_IP定位 = pd.json_normalize(IP定位)
df_IP定位


# # 批量请求接口

# ### 介绍  
# 批量接口通过用户传入合并后的请求，同时返回多个请求的顺序集合，目前最多支持20个子请求。 返回的顺序与子请求的顺序一致。
# 

# In[56]:


import requests
import json
import pandas as pd


# In[59]:


def batch(url="/v3/place/around?offset=10&page=1&key=99b6fd576c6cb06dc071b44d30935237&location=116.315196,39.959971&output=json&radius=100000&types=080000"):
    '''获取高德API批量请求接口'''
    parameters = {
        "key":key_jw,
    }
    body = {
        "ops":[
            {
                "url":'{}'.format(url)
            },
            {
                "url":"/v3/place/around?offset=10&page=1&key=99b6fd576c6cb06dc071b44d30935237&location=116.315196,39.959971&output=json&radius=100000&types=080000"
            }
        ]
    }
    response = requests.get("https://restapi.amap.com/v3/batch?",params = parameters,json=body)
    data = response.json()
    return data
batch()


# # 静态地图
# ### 介绍  
# 静态地图服务通过返回一张地图图片响应HTTP请求，使用户能够将高德地图以图片形式嵌入自己的网页中。用户可以指定请求的地图位置、图片大小、以及在地图上添加覆盖物，如标签、标注、折线、多边形。

# In[60]:


import requests
from PIL import Image
from io import BytesIO


# In[62]:


def staticmap(key,location="113.680117,23.631544",zoom=[1,17],size=None,scale=1,markers=None,labels=None,paths=None,traffic=0,sig=None,output=json)->dict:# 中山大学南方学院-综合楼
    '''获取高德API静态地图'''
    url = "https://restapi.amap.com/v3/staticmap?parameters"
    params = {
        "key":key_jw,
        "location":location,
        "zoom":zoom,
        "size":size,
        "markers":markers,
        "labels":labels,
        "paths":paths,
        "traffic":traffic,
        "sig":sig,
        "output":json
    }
    r = requests.get(url,params=params)
    result = Image.open(BytesIO(r.content))
    return result
staticmap(key= "key_jw",location="113.680117,23.631544",zoom=15)


# # 坐标转换
# ### 介绍
# 坐标转换是一类简单的HTTP接口，能够将用户输入的非高德坐标（GPS坐标、mapbar坐标、baidu坐标）转换成高德坐标。

# In[64]:


def convert(key,locations="113.679287,23.632575",coordsys=None,sig=None,output=json)->dict:
 '''获取坐标转换'''
 url = "https://restapi.amap.com/v3/assistant/coordinate/convert?parameters"
 params = {
     "key":key_jw,
     "locations":locations,
     "coordsys":coordsys,
     "sig":sig,
     "output":json
 }
 r = requests.get(url,params=params)
 result = r.json()
 return result
坐标转换 = convert(key="key_jw",locations="113.679287,23.632575")
print(坐标转换)
df_坐标转换 = pd.json_normalize(坐标转换)
df_坐标转换


# # 天气查询
# ### 介绍
# 天气查询是一个简单的HTTP接口，根据用户输入的adcode，查询目标区域当前/未来的天气情况。

# In[65]:


def weather(key,city='广州市',extensions=None,output=json)->dict:
    '''获取天气查询'''
    url = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'
    key = '5e511d55ece1791b213c4ef41b428738'
    params = {
        "key":key_jw,
        "city":city,
        "extensions":extensions,
        "output":json
    }
    r = requests.get(url,params=params)
    result = r.json()
    return result
weather_inquire = weather(key="key_jw",city="广州市")
print(weather_inquire)
df_weather_inquire = pd.json_normalize(weather_inquire)
df_weather_inquire


# # 输入提示
# ### 介绍
# 输入提示是一类简单的HTTP接口，提供根据用户输入的关键词查询返回建议列表。  
# 
# ### 适用场景
# 在高德客户端的使用场景，输入“仙林”之后出现提示相关。

# In[66]:


def inputtips(key,keywords='麦当劳',type=None,location=None,city=None,citylimit="true",datatype="all",sig=None,callback=None,output=json)->dict:
    '''获取高德API提示'''
    url = 'https://restapi.amap.com/v3/assistant/inputtips?parameters'
    key = '5e511d55ece1791b213c4ef41b428738'
    params = {
        "key":key_jw,
        "keywords":keywords,
        "type":type,
        "location":location,
        "city":city,
        "citylimit":citylimit,
        "datatype":datatype,
        "sig":sig,
        "callback":callback,
        "output":json
    }
    r = requests.get(url,params=params)
    result = r.json()
    return result
inputtips = inputtips(key="key_jw",keywords="麦当劳")
print(inputtips)
df_inputtips = pd.json_normalize(inputtips)
df_inputtips


# In[ ]:




